﻿using System.ServiceModel;
using UtfprLibrary.Communication.Contracts;
using UtfprLibrary.Exceptions;
using System;

namespace UtfprLibrary.Communication {
    /// <summary>
    /// TODO
    /// </summary>
    public class Publisher {
        private IPublishing _proxy;

        /// <summary>
        /// TODO
        /// </summary>
        /// <param name="endpointAddressUri"></param>
        public Publisher(string endpointAddressUri) {
            try {
                createProxy(endpointAddressUri);
            } catch (Exception ex) {
                throw new UtfprCommunicationException(Properties.Resources.Communication_Publisher_ExMsg_Publisher, ex);
            }
        }

        /// <summary>
        /// TODO
        /// </summary>
        /// <param name="message"></param>
        /// <param name="sujbect"></param>
        public void SendMessage(Message message, string sujbect) {
            try {
                _proxy.Publish(message, sujbect);
            } catch (Exception ex) {
                throw new UtfprCommunicationException(Properties.Resources.Communication_Publisher_ExMsg_SendMessage, ex);
            }
        }

        /// <summary>
        /// TODO
        /// </summary>
        /// <param name="endpointAddressUri"></param>
        private void createProxy(string endpointAddressUri) {
            try {
                EndpointAddress endpointAddress = new EndpointAddress(endpointAddressUri);
                NetTcpBinding netTcpBinding = new NetTcpBinding();
                _proxy = ChannelFactory<IPublishing>.CreateChannel(netTcpBinding, endpointAddress);
            } catch (Exception ex) {
                throw new UtfprCommunicationException("Could not create proxy.", ex);
            }
        }
    }
}
